package com.sxran.im.controller;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.sxran.im.bean.CommonResult;
import com.sxran.im.bean.ImException;
import com.sxran.im.service.CmdHandlerEnum;
import com.sxran.im.service.JWTService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

// http://127.0.0.1:18092/im/http/getContent
@RequestMapping("/im/http")
@RestController
@Slf4j
public class ImController {
    String privateKeyStr = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIy6lBCWr9Cr4kza3b5OPtiCwi65jE6UL6pgA0/jvY/xFWZYr8lyfSLEolj73/GC5udZECiJCPAEbr+W90+rVEeTTAIJYt7TAEJeQvOH0kPgarVtR8lcZaDAzRws6Wvkt18abwywWdUQkvMeL/Tt4vWBBImpxLOMNs7v3oGNccuvAgMBAAECgYAlJPID1uIc/+FBS9uPaXOpDgpW7t6btv1FyQXWxlO4dHejhfEQCMoCrUf0mLapNlXf5mAfctwLDgB1TVGFk8EwppJF2eQrHL/LgqYnVyix97QZ8AYLbretiwbw4qcLnsC3jCh2NjVWX9GlUX55bInsKHXbI8AA44vwZDdzK29TAQJBAM/PKbtydpJM3gn44BdVHZjHtGZxM5saYxIUgHDUE+vx4uJsdmh1+KxWpZBY+Be5fXCQa1PmzUTz6dFT3O5w10ECQQCtXRvYsq3L3GHlRO0HxI4EiQWGHQIxmtuceymblb07c9joxiQMlKztdI2tg3nROomFmvzV3Vt3dyraDWPYiVbvAkEAvmnxsFuSwD2E2xhbpaWNSBf9ejzR75Y/HysAAeKiGnl6zsRZvyAR60A91sVfFsYVZdY/MhLzFfJ11iQE9csZwQJBAJMER64f8KTWEqrUJdKVi/4qmOWfyhF5Cs4L4EAR3vUBDCxyg3Wry25fjhpcSbz2UFNeGRXgb0XDaDKcclTaOz8CP3tCCWpQojGuw4GEJPkTZiAcfctCQrG84uTEoDtc7z+zM56yZ6dxEe4VY2vrqsgk1FDuALwSXx+Jl8OwoFjU5Q==";

    private final static  ThreadLocal<String> TOKEN_THREAD_LOCAL = new ThreadLocal<>();

    @PostMapping(value = "/doService/{cmd}", consumes = "text/plain")
    @Transactional
    public String doService(@RequestHeader("X-KEY") String key ,@RequestHeader("X-TOKEN") String token ,@PathVariable(value = "cmd") Integer cmd, @RequestBody String encryptHex) {
        // 解密key 获得aes内容
        RSA rsa = new RSA(privateKeyStr,null);
        byte[] keyAESbytes = rsa.decrypt(key, KeyType.PrivateKey);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, keyAESbytes);
        String json = null;
        String response = null;
        CommonResult commonResult = new CommonResult();
        try{
            TOKEN_THREAD_LOCAL.set(token);
            // 解密传输过来的数据。
            json = aes.decryptStr(encryptHex, CharsetUtil.CHARSET_UTF_8);
            // 业务逻辑处理。
            response = CmdHandlerEnum.getCmdHandler(cmd).doService(json);
            commonResult.setCode(0);
            commonResult.setData(response);

        } catch (ImException e){
            log.error("ImException-----",e);
            commonResult.setCode(e.getCode());
            commonResult.setMsg(e.getMessage());
        }catch (Throwable e){
            log.error("Throwable-----",e);
            commonResult.setCode(501);
            commonResult.setMsg(e.getMessage());
        }finally {
            // log
            log.debug("cmd=[{}],token=[{}],json=[{}],response=[{}]",new Object[]{
                    cmd,token,json,commonResult
            } );
            TOKEN_THREAD_LOCAL.remove();
        }
        // 加密输出 out
        return  aes.encryptHex(JSONObject.toJSONString(commonResult));
    }
    /**
     * 获得当前的token。
     * @return
     */
    public static String getToken(){
        return TOKEN_THREAD_LOCAL.get();
    }
    /**
     * 获得当前登录的用户id。
     * @return
     */
    public static String getCurUserId(){
        String token = getToken();
        JWTService service = SpringUtil.getBean(JWTService.class);
        return service.getUserId(token);
    }

}
